package com.simCardTool.ui;

import java.io.DataOutputStream;

import com.simCardTool.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;

public class SimCardToolDialogActivity extends Activity {
    
	/** tag */
	private final static String TAG = "SimCardToolDialogActivity"; 
	
	/** is the user cancel */
	private static boolean USER_CANCEL_INDICATOR = false;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.i(TAG, "SimCardToolDialogActivity onCreate");
        
		//set the fly mode
        setAirplaneMode();
		
        //show the dialog to warn user shout down the device
        USER_CANCEL_INDICATOR = false;
        getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
        final AlertDialog dialog = new AlertDialog.Builder(this).setTitle("Error")
	        .setMessage("Please insert a SIM card in permission.")
			.setPositiveButton("Shutdown",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							shutdownDevice();
							SimCardToolDialogActivity.this.finish();
						}
					}).setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							dialog.dismiss();
							USER_CANCEL_INDICATOR = true;
							SimCardToolDialogActivity.this.finish();
						}
					}).create();
        dialog.setOnKeyListener(new OnKeyListener(){
            @Override  
            public boolean onKey(DialogInterface dialog, int keyCode,KeyEvent event) {  
            	Log.i(TAG,"keycode="+keyCode);
                return true;//return true so that all key event will not be handle
            }
        });
        dialog.show();
        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
	}
	
	/**
     * set the airplane mode
     */
    private void setAirplaneMode() {
    	Settings.System.putInt(getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 1);
        Intent localIntent = new Intent("android.intent.action.AIRPLANE_MODE").putExtra("state", true);
        sendBroadcast(localIntent);
    }
    
    /**
     * shutdown the device
     */
    private void shutdownDevice() {	
    	//get root permission
    	getRoot();
    	
    	//shutdown
    	Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
    	intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);//if need user confirm
    	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    	startActivity(intent);
    }
    
    /**
     * get root permission
     */
    private void getRoot() {
    	String apkRoot="chmod 777 "+getPackageCodePath(); 
    	RootCommand(apkRoot);
    }
    
    /**
     * run the command to get Root permission, the device must be root first or be the sysem app level
     * @param command：String apkRoot="chmod 777 "+getPackageCodePath(); RootCommand(apkRoot);
     * @return if get root permission
     */
    public static boolean RootCommand(String command) {  
        Process process = null;  
        DataOutputStream os = null;  
        try {  
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());  
            os.writeBytes(command + "\n");  
            os.writeBytes("exit\n");  
            os.flush();  
            process.waitFor();  
        } catch (Exception e) {  
            Log.d("*** DEBUG ***", "ROOT REE" + e.getMessage());  
            return false;  
        } finally {  
        	try {  
        		if (os != null) {  
                    os.close();  
                }  
                process.destroy();  
            } catch (Exception e) {  
            }  
        }  
        Log.d("*** DEBUG ***", "Root SUC ");  
        return true;  
    }
    
    
    @Override
    public void onDestroy() {
		super.onDestroy();
		if (!USER_CANCEL_INDICATOR) {//if not cancel by user, start the dialog again
			Intent startMain = new Intent(this, SimCardToolDialogActivity.class);
			startMain.setFlags(272629760);
			startActivity(startMain);
		}
	}

}